package com.dequan.springaiproject.manager;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.info.ProjectInfoProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class ChatClientManager {
    private CopyOnWriteArrayList<ChatClient> chatClients;
    private final AtomicInteger counter = new AtomicInteger(0);

    private ChatClientManager() {}

    public ChatClientManager(List<ChatClient> chatClients) {
        this.chatClients = new CopyOnWriteArrayList<>(chatClients);
    }

    private ChatClientManager(Builder builder) {
        this.chatClients = new CopyOnWriteArrayList<>(builder.chatClients);
    }

    /**
     * 根据轮询算法选择 ChatClient
     * @return ChatClient 实例
     */
    public ChatClient getNextChatClient() {
        int index = (counter.getAndIncrement() & 0x7fffffff) % chatClients.size();
        return chatClients.get(index);
    }

    /**
     * 根据随机算法选择 ChatClient
     * @return ChatClient 实例
     */
    public ChatClient getRandomChatClient() {
        int index = (int) (Math.random() * chatClients.size());
        return chatClients.get(index);
    }

    // static内部类 不依赖与外部类实例化
    public static class Builder {
        public List<ChatClient> chatClients = new ArrayList<>();

        public Builder addChatClient(ChatClient chatClient) {
            chatClients.add(chatClient);
            return this;
        }

        public ChatClientManager build() {
            return new ChatClientManager(this);
        }
    }
}